<!DOCTYPE html>
<html lang="zh" dir="ltr" class="client-nojs">
<head>
<title>复制消除</title>
<meta charset="UTF-8">
<meta name="generator" content="MediaWiki 1.21.2">
<link rel="shortcut icon" href="../../../common/favicon.ico">
<link rel="stylesheet" href="../../../common/ext.css">
<meta name="ResourceLoaderDynamicStyles" content="">
<link rel="stylesheet" href="../../../common/site_modules.css">
<style>a:lang(ar),a:lang(ckb),a:lang(fa),a:lang(kk-arab),a:lang(mzn),a:lang(ps),a:lang(ur){text-decoration:none}#toc{display:none}.editsection{display:none}
/* cache key: mwiki1-mwiki_zh_:resourceloader:filter:minify-css:7:15cea3ec788a65b5187d4018eed543bf */</style>

<script src="../../../common/startup_scripts.js"></script>
<script>if(window.mw){
mw.config.set({"wgCanonicalNamespace":"","wgCanonicalSpecialPageName":false,"wgNamespaceNumber":0,"wgPageName":"cpp/language/copy_elision","wgTitle":"cpp/language/copy elision","wgCurRevisionId":65259,"wgArticleId":2696,"wgIsArticle":true,"wgAction":"view","wgUserName":null,"wgUserGroups":["*"],"wgCategories":[],"wgBreakFrames":false,"wgPageContentLanguage":"zh","wgSeparatorTransformTable":["",""],"wgDigitTransformTable":["",""],"wgDefaultDateFormat":"zh","wgMonthNames":["","1月","2月","3月","4月","5月","6月","7月","8月","9月","10月","11月","12月"],"wgMonthNamesShort":["","1月","2月","3月","4月","5月","6月","7月","8月","9月","10月","11月","12月"],"wgRelevantPageName":"cpp/language/copy_elision","wgUserVariant":"zh","wgRestrictionEdit":[],"wgRestrictionMove":[]});
}</script><script>if(window.mw){
mw.loader.implement("user.options",function(){mw.user.options.set({"ccmeonemails":0,"cols":80,"date":"default","diffonly":0,"disablemail":0,"disablesuggest":0,"editfont":"default","editondblclick":0,"editsection":0,"editsectiononrightclick":0,"enotifminoredits":0,"enotifrevealaddr":0,"enotifusertalkpages":1,"enotifwatchlistpages":0,"extendwatchlist":0,"externaldiff":0,"externaleditor":0,"fancysig":0,"forceeditsummary":0,"gender":"unknown","hideminor":0,"hidepatrolled":0,"imagesize":2,"justify":0,"math":1,"minordefault":0,"newpageshidepatrolled":0,"nocache":0,"noconvertlink":0,"norollbackdiff":0,"numberheadings":0,"previewonfirst":0,"previewontop":1,"quickbar":5,"rcdays":7,"rclimit":50,"rememberpassword":0,"rows":25,"searchlimit":20,"showhiddencats":0,"showjumplinks":1,"shownumberswatching":1,"showtoc":0,"showtoolbar":1,"skin":"cppreference2","stubthreshold":0,"thumbsize":2,"underline":2,"uselivepreview":0,"usenewrc":0,"watchcreations":0,"watchdefault":0,"watchdeletion":0,
"watchlistdays":3,"watchlisthideanons":0,"watchlisthidebots":0,"watchlisthideliu":0,"watchlisthideminor":0,"watchlisthideown":0,"watchlisthidepatrolled":0,"watchmoves":0,"wllimit":250,"variant":"zh","language":"zh","searchNs0":true,"searchNs1":false,"searchNs2":false,"searchNs3":false,"searchNs4":false,"searchNs5":false,"searchNs6":false,"searchNs7":false,"searchNs8":false,"searchNs9":false,"searchNs10":false,"searchNs11":false,"searchNs12":false,"searchNs13":false,"searchNs14":false,"searchNs15":false,"gadget-MathJax":1,"gadget-ColiruCompiler":1});;},{},{});mw.loader.implement("user.tokens",function(){mw.user.tokens.set({"editToken":"+\\","patrolToken":false,"watchToken":false});;},{},{});
/* cache key: mwiki1-mwiki_zh_:resourceloader:filter:minify-js:7:258d7cd6aa9aa67dee25e01fb6a9e505 */
}</script>
<script>if(window.mw){
mw.loader.load(["mediawiki.page.startup","mediawiki.legacy.wikibits","mediawiki.legacy.ajax"]);
}</script>
<style type="text/css">/*<![CDATA[*/
.source-cpp {line-height: normal;}
.source-cpp li, .source-cpp pre {
	line-height: normal; border: 0px none white;
}
/**
 * GeSHi Dynamically Generated Stylesheet
 * --------------------------------------
 * Dynamically generated stylesheet for cpp
 * CSS class: source-cpp, CSS id: 
 * GeSHi (C) 2004 - 2007 Nigel McNie, 2007 - 2008 Benny Baumann
 * (http://qbnz.com/highlighter/ and http://geshi.org/)
 * --------------------------------------
 */
.cpp.source-cpp .de1, .cpp.source-cpp .de2 {font: normal normal 1em/1.2em monospace; margin:0; padding:0; background:none; vertical-align:top;}
.cpp.source-cpp  {font-family:monospace;}
.cpp.source-cpp .imp {font-weight: bold; color: red;}
.cpp.source-cpp li, .cpp.source-cpp .li1 {font-weight: normal; vertical-align:top;}
.cpp.source-cpp .ln {width:1px;text-align:right;margin:0;padding:0 2px;vertical-align:top;}
.cpp.source-cpp .li2 {font-weight: bold; vertical-align:top;}
.cpp.source-cpp .kw1 {color: #0000dd;}
.cpp.source-cpp .kw2 {color: #0000ff;}
.cpp.source-cpp .kw3 {color: #0000dd;}
.cpp.source-cpp .kw4 {color: #0000ff;}
.cpp.source-cpp .co1 {color: #909090;}
.cpp.source-cpp .co2 {color: #339900;}
.cpp.source-cpp .coMULTI {color: #ff0000; font-style: italic;}
.cpp.source-cpp .es0 {color: #008000; font-weight: bold;}
.cpp.source-cpp .es1 {color: #008000; font-weight: bold;}
.cpp.source-cpp .es2 {color: #008000; font-weight: bold;}
.cpp.source-cpp .es3 {color: #008000; font-weight: bold;}
.cpp.source-cpp .es4 {color: #008000; font-weight: bold;}
.cpp.source-cpp .es5 {color: #008000; font-weight: bold;}
.cpp.source-cpp .br0 {color: #008000;}
.cpp.source-cpp .sy0 {color: #008000;}
.cpp.source-cpp .sy1 {color: #000080;}
.cpp.source-cpp .sy2 {color: #000040;}
.cpp.source-cpp .sy3 {color: #000040;}
.cpp.source-cpp .sy4 {color: #008080;}
.cpp.source-cpp .st0 {color: #008000;}
.cpp.source-cpp .nu0 {color: #000080;}
.cpp.source-cpp .nu6 {color: #000080;}
.cpp.source-cpp .nu8 {color: #000080;}
.cpp.source-cpp .nu12 {color: #000080;}
.cpp.source-cpp .nu16 {color:#000080;}
.cpp.source-cpp .nu17 {color:#000080;}
.cpp.source-cpp .nu18 {color:#000080;}
.cpp.source-cpp .nu19 {color:#000080;}
.cpp.source-cpp .ln-xtra, .cpp.source-cpp li.ln-xtra, .cpp.source-cpp div.ln-xtra {background-color: #ffc;}
.cpp.source-cpp span.xtra { display:block; }

/*]]>*/
</style><style type="text/css">/*<![CDATA[*/
.source-text {line-height: normal;}
.source-text li, .source-text pre {
	line-height: normal; border: 0px none white;
}
/**
 * GeSHi Dynamically Generated Stylesheet
 * --------------------------------------
 * Dynamically generated stylesheet for text
 * CSS class: source-text, CSS id: 
 * GeSHi (C) 2004 - 2007 Nigel McNie, 2007 - 2008 Benny Baumann
 * (http://qbnz.com/highlighter/ and http://geshi.org/)
 * --------------------------------------
 */
.text.source-text .de1, .text.source-text .de2 {font: normal normal 1em/1.2em monospace; margin:0; padding:0; background:none; vertical-align:top;}
.text.source-text  {font-family:monospace;}
.text.source-text .imp {font-weight: bold; color: red;}
.text.source-text li, .text.source-text .li1 {font-weight: normal; vertical-align:top;}
.text.source-text .ln {width:1px;text-align:right;margin:0;padding:0 2px;vertical-align:top;}
.text.source-text .li2 {font-weight: bold; vertical-align:top;}
.text.source-text .ln-xtra, .text.source-text li.ln-xtra, .text.source-text div.ln-xtra {background-color: #ffc;}
.text.source-text span.xtra { display:block; }

/*]]>*/
</style><!--[if lt IE 7]><style type="text/css">body{behavior:url("/mwiki/skins/cppreference2/csshover.min.htc")}</style><![endif]--></head>
<body class="mediawiki ltr sitedir-ltr ns-0 ns-subject page-cpp_language_copy_elision skin-cppreference2 action-view cpp-navbar">
        <!-- header -->
        <!-- /header -->
        <!-- content -->
<div id="cpp-content-base">
            <div id="content">
                <a id="top"></a>
                <div id="mw-js-message" style="display:none;"></div>
                                <!-- firstHeading -->
<h1 id="firstHeading" class="firstHeading">复制消除</h1>
                <!-- /firstHeading -->
                <!-- bodyContent -->
                <div id="bodyContent">
                                        <!-- tagline -->
                    <div id="siteSub">来自cppreference.com</div>
                    <!-- /tagline -->
                                        <!-- subtitle -->
                    <div id="contentSub"><span class="subpages">&lt; <a href="../../cpp.html" title="cpp">cpp</a>‎ | <a href="../language.html" title="cpp/language">language</a></span></div>
                    <!-- /subtitle -->
                                                            <!-- bodycontent -->
                    <div id="mw-content-text" lang="zh" dir="ltr" class="mw-content-ltr"><div class="t-navbar" style=""><div class="t-navbar-sep"> </div><div class="t-navbar-head"><a href="../../cpp.html" title="cpp"> C++</a><div class="t-navbar-menu"><div><div><table class="t-nv-begin" cellpadding="0" style="line-height:1.1em;">
<tr class="t-nv"><td colspan="5"> <a href="../language.html" title="cpp/language">语言</a> </td></tr>
<tr class="t-nv"><td colspan="5"> <a href="../header.html" title="cpp/header">标准库头文件</a> </td></tr>
<tr class="t-nv"><td colspan="5"> <a href="../freestanding.html" title="cpp/freestanding"> 自立与有宿主实现</a> </td></tr>
<tr class="t-nv"><td colspan="5"> <a href="../named_req.html" title="cpp/named req">具名要求</a> </td></tr>
<tr class="t-nv"><td colspan="5"> <a href="../utility.html#.E8.AF.AD.E8.A8.80.E6.94.AF.E6.8C.81" title="cpp/utility">语言支持库</a> </td></tr>
<tr class="t-nv"><td colspan="5"> <a href="../concepts.html" title="cpp/concepts">概念库</a> <span class="t-mark-rev t-since-cxx20">(C++20)</span> </td></tr>
<tr class="t-nv"><td colspan="5"> <a href="../error.html" title="cpp/error">诊断库</a> </td></tr>
<tr class="t-nv"><td colspan="5"> <a href="../utility.html" title="cpp/utility">工具库</a> </td></tr>
<tr class="t-nv"><td colspan="5"> <a href="../string.html" title="cpp/string">字符串库</a> </td></tr>
<tr class="t-nv"><td colspan="5"> <a href="https://zh.cppreference.com/w/cpp/container" title="cpp/container">容器库</a> </td></tr>
<tr class="t-nv"><td colspan="5"> <a href="../iterator.html" title="cpp/iterator">迭代器库</a> </td></tr>
<tr class="t-nv"><td colspan="5"> <a href="../ranges.html" title="cpp/ranges"> 范围库</a> <span class="t-mark-rev t-since-cxx20">(C++20)</span> </td></tr>
<tr class="t-nv"><td colspan="5"> <a href="../algorithm.html" title="cpp/algorithm">算法库</a> </td></tr>
<tr class="t-nv"><td colspan="5"> <a href="../numeric.html" title="cpp/numeric">数值库</a> </td></tr>
<tr class="t-nv"><td colspan="5"> <a href="../io.html" title="cpp/io">输入/输出库</a> </td></tr>
<tr class="t-nv"><td colspan="5"> <a href="../locale.html" title="cpp/locale">本地化库</a> </td></tr>
<tr class="t-nv"><td colspan="5"> <a href="../regex.html" title="cpp/regex">正则表达式库</a> <span class="t-mark-rev t-since-cxx11">(C++11)</span> </td></tr>
<tr class="t-nv"><td colspan="5"> <a href="../atomic.html" title="cpp/atomic">原子操作库</a> <span class="t-mark-rev t-since-cxx11">(C++11)</span> </td></tr>
<tr class="t-nv"><td colspan="5"> <a href="../thread.html" title="cpp/thread">线程支持库</a> <span class="t-mark-rev t-since-cxx11">(C++11)</span> </td></tr>
<tr class="t-nv"><td colspan="5"> <a href="../filesystem.html" title="cpp/filesystem">文件系统库</a> <span class="t-mark-rev t-since-cxx17">(C++17)</span> </td></tr>
<tr class="t-nv"><td colspan="5"> <a href="../experimental.html" title="cpp/experimental">技术规范</a> </td></tr>
</table></div><div></div></div></div></div><div class="t-navbar-sep"> </div><div class="t-navbar-head"><a href="../language.html" title="cpp/language">C++ 语言</a></div><div class="t-navbar-sep"> </div><div class="t-navbar-head"><a href="initialization.html" title="cpp/language/initialization">初始化</a><div class="t-navbar-menu"><div><div style="display:inline-block">
<div><table class="t-nv-begin" cellpadding="0" style="">
<tr class="t-nv-h2"><td colspan="5"><a href="initialization.html" title="cpp/language/initialization">初始化器</a></td></tr>
<tr class="t-nv"><td colspan="5"><a href="default_initialization.html" title="cpp/language/default initialization">默认初始化</a></td></tr>
<tr class="t-nv"><td colspan="5"><a href="value_initialization.html" title="cpp/language/value initialization">值初始化</a></td></tr>
<tr class="t-nv"><td colspan="5"><a href="direct_initialization.html" title="cpp/language/direct initialization">直接初始化</a></td></tr>
<tr class="t-nv"><td colspan="5"><a href="copy_initialization.html" title="cpp/language/copy initialization">复制初始化</a></td></tr>
<tr class="t-nv"><td colspan="5"><a href="list_initialization.html" title="cpp/language/list initialization">列表初始化</a></td></tr>
<tr class="t-nv"><td colspan="5"><a href="aggregate_initialization.html" title="cpp/language/aggregate initialization">聚合初始化</a></td></tr>
<tr class="t-nv"><td colspan="5"><a href="reference_initialization.html" title="cpp/language/reference initialization">引用初始化</a></td></tr>
<tr class="t-nv"><td colspan="5"><strong class="selflink">复制消除</strong></td></tr>
<tr class="t-nv-h2"><td colspan="5"><a href="initialization.html#.E9.9D.9E.E5.B1.80.E9.83.A8.E5.8F.98.E9.87.8F" title="cpp/language/initialization">静态初始化</a></td></tr>
<tr class="t-nv"><td colspan="5"><a href="zero_initialization.html" title="cpp/language/zero initialization">零初始化</a></td></tr>
<tr class="t-nv"><td colspan="5"><a href="constant_initialization.html" title="cpp/language/constant initialization">常量初始化</a></td></tr>
<tr class="t-nv-h2"><td colspan="5"><a href="initialization.html#.E9.9D.9E.E5.B1.80.E9.83.A8.E5.8F.98.E9.87.8F" title="cpp/language/initialization">动态非局部初始化</a></td></tr>
<tr class="t-nv"><td colspan="5"><a href="initialization.html#.E9.9D.9E.E5.B1.80.E9.83.A8.E5.8F.98.E9.87.8F" title="cpp/language/initialization">有序动态初始化</a></td></tr>
<tr class="t-nv"><td colspan="5"><a href="initialization.html#.E9.9D.9E.E5.B1.80.E9.83.A8.E5.8F.98.E9.87.8F" title="cpp/language/initialization">无序动态初始化</a></td></tr>
<tr class="t-nv-h2"><td colspan="5">类成员初始化</td></tr>
<tr class="t-nv"><td colspan="5"><a href="constructor.html" title="cpp/language/initializer list">成员初始化器列表</a></td></tr>
<tr class="t-nv"><td colspan="5"><a href="data_members.html#.E6.88.90.E5.91.98.E5.88.9D.E5.A7.8B.E5.8C.96" title="cpp/language/data members">类内<i>花括号或等号</i>初始化器</a></td></tr>
</table></div>
</div><div></div></div></div></div><div class="t-navbar-sep"> </div></div>
<p>省略复制<span class="t-rev-inl t-since-cxx11"><span>及移动</span> <span><span class="t-mark-rev t-since-cxx11">(C++11 起)</span></span></span>构造函数，导致零复制的按值传递语义。
</p>
<h3><span class="mw-headline" id=".E8.A7.A3.E9.87.8A">解释</span></h3>
 <table class="t-rev-begin">
<tr class="t-rev t-since-cxx17"><td>
<h4> <span class="mw-headline" id=".E5.BC.BA.E5.88.B6.E7.9A.84.E5.A4.8D.E5.88.B6.2F.E7.A7.BB.E5.8A.A8.E6.93.8D.E4.BD.9C.E6.B6.88.E9.99.A4">强制的复制/移动操作消除</span></h4>
<p>下列环境下，要求编译器省略类对象的复制和移动构造，即使复制/移动构造函数和析构函数拥有可观察副作用。直接将对象构造到它们本来要复制/移动到的存储中。复制/移动构造函数不必存在或可访问：
</p>
<ul><li> 在 <a href="return.html" title="cpp/language/return">return 语句</a>中，当操作数为与函数返回类型为同一类类型的<a href="value_category.html" title="cpp/language/value category">纯右值</a>（忽略 <a href="cv.html" title="cpp/language/cv">cv 限定</a>）时：
</li></ul>
<div dir="ltr" class="mw-geshi" style="text-align: left;"><div class="cpp source-cpp"><pre class="de1">T f<span class="br0">(</span><span class="br0">)</span> <span class="br0">{</span>
    <span class="kw1">return</span> T<span class="br0">(</span><span class="br0">)</span><span class="sy4">;</span>
<span class="br0">}</span>
 
f<span class="br0">(</span><span class="br0">)</span><span class="sy4">;</span> <span class="co1">// 仅调用一次 T 的默认构造函数</span></pre></div></div>
<dl><dd>  返回类型的析构函数必须在 return 语句位置可访问且未被删除，即使无待销毁的 T 对象。
</dd></dl>
<ul><li> 在对象的初始化中，当初始化器表达式为与变量类型为同一类类型的<a href="value_category.html" title="cpp/language/value category">纯右值</a>（忽略 <a href="cv.html" title="cpp/language/cv">cv 限定</a>）时：
</li></ul>
<div dir="ltr" class="mw-geshi" style="text-align: left;"><div class="cpp source-cpp"><pre class="de1">T x <span class="sy1">=</span> T<span class="br0">(</span>T<span class="br0">(</span>f<span class="br0">(</span><span class="br0">)</span><span class="br0">)</span><span class="br0">)</span><span class="sy4">;</span> <span class="co1">// 仅调用一次 T 的默认构造函数以初始化 x</span></pre></div></div>
<dl><dd> 这仅能在已知待初始化对象不是潜在重叠的子对象时应用：
</dd></dl>
<div dir="ltr" class="mw-geshi" style="text-align: left;"><div class="cpp source-cpp"><pre class="de1"><span class="kw1">struct</span> C <span class="br0">{</span> <span class="coMULTI">/* ... */</span> <span class="br0">}</span><span class="sy4">;</span>
C f<span class="br0">(</span><span class="br0">)</span><span class="sy4">;</span>
<span class="kw1">struct</span> D<span class="sy4">;</span>
D g<span class="br0">(</span><span class="br0">)</span><span class="sy4">;</span>
<span class="kw1">struct</span> D <span class="sy4">:</span> C <span class="br0">{</span>
    D<span class="br0">(</span><span class="br0">)</span> <span class="sy4">:</span> C<span class="br0">(</span>f<span class="br0">(</span><span class="br0">)</span><span class="br0">)</span> <span class="br0">{</span> <span class="br0">}</span>    <span class="co1">// 初始化基类子对象时无消除</span>
    D<span class="br0">(</span><span class="kw4">int</span><span class="br0">)</span> <span class="sy4">:</span> D<span class="br0">(</span>g<span class="br0">(</span><span class="br0">)</span><span class="br0">)</span> <span class="br0">{</span> <span class="br0">}</span> <span class="co1">// 无消除，因为正在初始化的 D 对象可能为某个其他类的基类子对象</span>
<span class="br0">}</span><span class="sy4">;</span></pre></div></div>
<p>注意：上述规则并不指定优化：针对<a href="value_category.html" title="cpp/language/value category">纯右值</a>和<a href="implicit_cast.html#.E4.B8.B4.E6.97.B6.E9.87.8F.E5.AE.9E.E8.B4.A8.E5.8C.96" title="cpp/language/implicit conversion">临时量</a>的 C++17 核心语言规定本质上不同于之前的 C++ 版本：不再有用以复制/移动的临时量。描述 C++17 语义的另一种方式是“传递未实质化的值”：返回并使用纯右值时不实质化临时量。
</p>
</td>
<td><span class="t-mark-rev t-since-cxx17">(C++17 起)</span></td></tr>
</table>
<h4><span class="mw-headline" id=".E9.9D.9E.E5.BC.BA.E5.88.B6.E7.9A.84.E5.A4.8D.E5.88.B6.2F.E7.A7.BB.E5.8A.A8_.28C.2B.2B11_.E8.B5.B7.29.E6.93.8D.E4.BD.9C.E6.B6.88.E9.99.A4">非强制的复制<span class="t-rev-inl t-since-cxx11"><span>/移动</span> <span><span class="t-mark-rev t-since-cxx11">(C++11 起)</span></span></span>操作消除</span></h4>
<p>下列环境下，容许但不要求编译器省略类对象的复制<span class="t-rev-inl t-since-cxx11"><span>和移动</span> <span><span class="t-mark-rev t-since-cxx11">(C++11 起)</span></span></span>构造，即使复制<span class="t-rev-inl t-since-cxx11"><span>/移动</span> <span><span class="t-mark-rev t-since-cxx11">(C++11 起)</span></span></span>构造函数和析构函数拥有可观察副作用。直接将对象构造到它们本来要复制/移动到的存储中。这是一项优化：即使进行了优化而不调用复制<span class="t-rev-inl t-since-cxx11"><span>/移动</span> <span><span class="t-mark-rev t-since-cxx11">(C++11 起)</span></span></span>构造函数，它仍然必须存在且可访问（如同完全未发生优化），否则程序非良构：
</p>
<ul><li> <a href="return.html" title="cpp/language/return">return 语句</a>中，当操作数是拥有自动存储期的非 volatile 对象的名字，其并非函数形参或 catch 子句形参，且其具有与函数返回类型相同的类类型（忽略 <a href="cv.html" title="cpp/language/cv">cv 限定</a>）时。这种复制消除的变体被称为 NRVO，“具名返回值优化 (named return value optimization)”。
</li></ul>
 <table class="t-rev-begin">
<tr class="t-rev t-until-cxx17"><td>
<ul><li> 在对象的初始化中，当源对象是无名临时量且与目标对象具有相同类型（忽略 <a href="cv.html" title="cpp/language/cv">cv 限定</a>）时。当无名临时量为 return 语句的操作数时，称这种复制消除的变体为 RVO，“返回值优化 (return value optimization)”。
</li></ul>
</td>
<td><span class="t-mark-rev t-until-cxx17">(C++17 前)</span></td></tr>
<tr class="t-rev t-since-cxx17"><td>
<p>返回值优化是强制要求的，而不再被当做复制消除；见上文。
</p>
</td>
<td><span class="t-mark-rev t-since-cxx17">(C++17 起)</span></td></tr>
</table>
 <table class="t-rev-begin">
<tr class="t-rev t-since-cxx11"><td>
<ul><li> <a href="throw.html" title="cpp/language/throw">throw 表达式</a>中，当操作数是具有自动存储期的非 volatile 对象的名字，其并非函数形参或 catch 子句形参，且其作用域不延伸超过最内层的 try 块（若有 try 块）时。
</li><li> <a href="try_catch.html" title="cpp/language/try catch">catch 子句</a>中，当实参与抛出的异常对象具有相同类型（忽略 <a href="cv.html" title="cpp/language/cv">cv 限定</a>）时，省略异常对象的复制，而该 catch 子句体直接访问该异常对象，如同按引用捕获它一样（不可能从异常对象移动，因为它始终是左值）。如果这种复制消除会因为除了跳过该 catch 子句形参的复制构造函数和析构函数之外的任何原因，导致程序的可观察行为发生改变，则它被禁止（例如，当修改了 catch 子句的实参，并以 <span class="t-c"><span class="mw-geshi cpp source-cpp"><span class="kw1">throw</span></span></span> 重新抛出异常对象时）。
</li></ul>
</td>
<td><span class="t-mark-rev t-since-cxx11">(C++11 起)</span></td></tr>
<tr class="t-rev t-since-cxx20"><td>
<ul><li> 在<a href="coroutines.html" title="cpp/language/coroutines">协程</a>中，可以消除将形参向协程状态内的复制/移动，只要除了对形参的构造函数与析构函数的调用被忽略以外，不改变程序的行为即可。若在暂停点后始终不使用形参，或者整个协程状态本就始终不在堆上分配，则可出现此情形。
</li></ul>
</td>
<td><span class="t-mark-rev t-since-cxx20">(C++20 起)</span></td></tr>
</table>
<p>进行复制消除时，实现将被省略的复制<span class="t-rev-inl t-since-cxx11"><span>/移动</span> <span><span class="t-mark-rev t-since-cxx11">(C++11 起)</span></span></span>操作的源和目标，单纯地当做指代同一对象的两种不同方式，而该对象的销毁，发生于假如不进行优化时两个对象本应被析构的时机的较迟者<span class="t-rev-inl t-since-cxx17"><span>（但若被选择的构造函数的形参是对象类型的右值引用，则其销毁发生于目标对象本应被销毁时）</span> <span><span class="t-mark-rev t-since-cxx17">(C++17 起)</span></span></span>。
</p><p>可以连锁多次复制消除，以消除多次复制。
</p>
 <table class="t-rev-begin">
<tr class="t-rev t-since-cxx14"><td>
<ul><li> 在<a href="constant_expression.html" title="cpp/language/constant expression">常量表达式</a>和<a href="constant_initialization.html" title="cpp/language/constant initialization">常量初始化</a>中，保证进行返回值优化（RVO），但禁止具名返回值优化（NRVO）：
</li></ul>
<div dir="ltr" class="mw-geshi" style="text-align: left;"><div class="cpp source-cpp"><pre class="de1"><span class="kw1">struct</span> A <span class="br0">{</span>
    <span class="kw4">void</span> <span class="sy2">*</span>p<span class="sy4">;</span>
    <span class="kw4">constexpr</span> A<span class="br0">(</span><span class="br0">)</span><span class="sy4">:</span> p<span class="br0">(</span>this<span class="br0">)</span> <span class="br0">{</span><span class="br0">}</span>
<span class="br0">}</span><span class="sy4">;</span>
 
<span class="kw4">constexpr</span> A g<span class="br0">(</span><span class="br0">)</span>
<span class="br0">{</span>
    A a<span class="sy4">;</span>
    <span class="kw1">return</span> a<span class="sy4">;</span>
<span class="br0">}</span>
 
<span class="kw4">constexpr</span> A a<span class="sy4">;</span>          <span class="co1">// a.p 指向 a</span>
<span class="co1">// constexpr A b = g(); // 错误： b.p 会悬垂，并会指向有自动存储期的临时量</span>
 
<span class="kw4">void</span> h<span class="br0">(</span><span class="br0">)</span>
<span class="br0">{</span>
    A c <span class="sy1">=</span> g<span class="br0">(</span><span class="br0">)</span><span class="sy4">;</span>          <span class="co1">// c.p 可能指向 c 或转瞬即逝的临时量</span>
<span class="br0">}</span>
 
<span class="kw4">extern</span> <span class="kw4">const</span> A d<span class="sy4">;</span> 
<span class="kw4">constexpr</span> A f<span class="br0">(</span><span class="br0">)</span>
<span class="br0">{</span>
    A e<span class="sy4">;</span>
    <span class="kw1">if</span> <span class="br0">(</span><span class="sy3">&amp;</span>e <span class="sy1">==</span> <span class="sy3">&amp;</span>d<span class="br0">)</span>
        <span class="kw1">return</span> A<span class="br0">(</span><span class="br0">)</span><span class="sy4">;</span>
    <span class="kw1">else</span>
        <span class="kw1">return</span> e<span class="sy4">;</span>
    <span class="co1">// 在常量求值中强制 NRVO 会导致矛盾，即当且仅当不执行 NRVO 时执行 NRVO</span>
<span class="br0">}</span> 
<span class="co1">// constexpr A d = f(); // 错误： d.p 悬垂</span></pre></div></div>
</td>
<td><span class="t-mark-rev t-since-cxx14">(C++14 起)</span></td></tr>
</table>
<h3><span class="mw-headline" id=".E6.B3.A8.E8.A7.A3">注解</span></h3>
<p>复制消除是允许改变可观察副作用的<span class="t-rev-inl t-until-cxx14"><span>唯一得到允许的优化形式</span> <span><span class="t-mark-rev t-until-cxx14">(C++14 前)</span></span></span><span class="t-rev-inl t-since-cxx14"><span>两种允许的优化形式之一，另一种是<a href="new.html#.E5.88.86.E9.85.8D" title="cpp/language/new">分配消除与扩展</a></span> <span><span class="t-mark-rev t-since-cxx14">(C++14 起)</span></span></span>。因为一些编译器并不在所有允许的场合中进行复制消除（例如 debug 模式下），依赖于复制/移动构造函数和析构函数的副作用的程序是不可移植的。
</p>
 <table class="t-rev-begin">
<tr class="t-rev t-since-cxx11"><td>
<p>在 return 语句或 throw 表达式中，若编译器不能进行复制消除，但满足或本应满足复制消除的条件（不含源是函数形参的情况），即使对象由左值代表，编译器也将尝试使用移动构造函数；细节见 <a href="return.html#.E6.B3.A8.E8.A7.A3" title="cpp/language/return">return 语句</a>。
</p>
</td>
<td><span class="t-mark-rev t-since-cxx11">(C++11 起)</span></td></tr>
</table>
<h3><span class="mw-headline" id=".E7.A4.BA.E4.BE.8B">示例</span></h3>
<div class="t-example"><div class="t-example-live-link"><div class="coliru-btn coliru-btn-run-init">运行此代码</div></div>
<div dir="ltr" class="mw-geshi" style="text-align: left;"><div class="cpp source-cpp"><pre class="de1"><span class="co2">#include &lt;iostream&gt;</span>
<span class="co2">#include &lt;vector&gt;</span>
 
<span class="kw1">struct</span> Noisy <span class="br0">{</span>
    Noisy<span class="br0">(</span><span class="br0">)</span> <span class="br0">{</span> <a href="../io/cout.html"><span class="kw1758">std::<span class="me2">cout</span></span></a> <span class="sy1">&lt;&lt;</span> <span class="st0">"constructed<span class="es1">\n</span>"</span><span class="sy4">;</span> <span class="br0">}</span>
    Noisy<span class="br0">(</span><span class="kw4">const</span> Noisy<span class="sy3">&amp;</span><span class="br0">)</span> <span class="br0">{</span> <a href="../io/cout.html"><span class="kw1758">std::<span class="me2">cout</span></span></a> <span class="sy1">&lt;&lt;</span> <span class="st0">"copy-constructed<span class="es1">\n</span>"</span><span class="sy4">;</span> <span class="br0">}</span>
    Noisy<span class="br0">(</span>Noisy<span class="sy3">&amp;&amp;</span><span class="br0">)</span> <span class="br0">{</span> <a href="../io/cout.html"><span class="kw1758">std::<span class="me2">cout</span></span></a> <span class="sy1">&lt;&lt;</span> <span class="st0">"move-constructed<span class="es1">\n</span>"</span><span class="sy4">;</span> <span class="br0">}</span>
    ~Noisy<span class="br0">(</span><span class="br0">)</span> <span class="br0">{</span> <a href="../io/cout.html"><span class="kw1758">std::<span class="me2">cout</span></span></a> <span class="sy1">&lt;&lt;</span> <span class="st0">"destructed<span class="es1">\n</span>"</span><span class="sy4">;</span> <span class="br0">}</span>
<span class="br0">}</span><span class="sy4">;</span>
 
<a href="../container/vector.html"><span class="kw1269">std::<span class="me2">vector</span></span></a><span class="sy1">&lt;</span>Noisy<span class="sy1">&gt;</span> f<span class="br0">(</span><span class="br0">)</span> <span class="br0">{</span>
    <a href="../container/vector.html"><span class="kw1269">std::<span class="me2">vector</span></span></a><span class="sy1">&lt;</span>Noisy<span class="sy1">&gt;</span> v <span class="sy1">=</span> <a href="../container/vector.html"><span class="kw1269">std::<span class="me2">vector</span></span></a><span class="sy1">&lt;</span>Noisy<span class="sy1">&gt;</span><span class="br0">(</span><span class="nu0">3</span><span class="br0">)</span><span class="sy4">;</span> <span class="co1">// 从临时量 (C++17 前)</span>
                                                  <span class="co1">// 从纯右值 (C++17 起)</span>
                                                  <span class="co1">// 初始化 v 中的复制消除</span>
    <span class="kw1">return</span> v<span class="sy4">;</span> <span class="co1">// 从 v 到结果对象的 NRVO（C++17 中仍不保证）</span>
<span class="br0">}</span>             <span class="co1">// 若禁用优化，则调用移动构造函数</span>
 
<span class="kw4">void</span> g<span class="br0">(</span><a href="../container/vector.html"><span class="kw1269">std::<span class="me2">vector</span></span></a><span class="sy1">&lt;</span>Noisy<span class="sy1">&gt;</span> arg<span class="br0">)</span> <span class="br0">{</span>
    <a href="../io/cout.html"><span class="kw1758">std::<span class="me2">cout</span></span></a> <span class="sy1">&lt;&lt;</span> <span class="st0">"arg.size() = "</span> <span class="sy1">&lt;&lt;</span> arg.<span class="me1">size</span><span class="br0">(</span><span class="br0">)</span> <span class="sy1">&lt;&lt;</span> <span class="st0">'<span class="es1">\n</span>'</span><span class="sy4">;</span>
<span class="br0">}</span>
 
<span class="kw4">int</span> main<span class="br0">(</span><span class="br0">)</span> <span class="br0">{</span>
    <a href="../container/vector.html"><span class="kw1269">std::<span class="me2">vector</span></span></a><span class="sy1">&lt;</span>Noisy<span class="sy1">&gt;</span> v <span class="sy1">=</span> f<span class="br0">(</span><span class="br0">)</span><span class="sy4">;</span> <span class="co1">// 从 f() 返回的临时量 (C++17 前)</span>
                                <span class="co1">// 从纯右值 f() (C++17 起)</span>
                                <span class="co1">// 初始化 v 中的复制消除</span>
    g<span class="br0">(</span>f<span class="br0">(</span><span class="br0">)</span><span class="br0">)</span><span class="sy4">;</span>                     <span class="co1">// 从 f() 返回的临时量 (C++17 前)</span>
                                <span class="co1">// 从纯右值 f() (C++17 起)</span>
                                <span class="co1">// 初始化 g() 的形参中的复制消除</span>
<span class="br0">}</span></pre></div></div>
<p>可能的输出：
</p>
<div dir="ltr" class="mw-geshi" style="text-align: left;"><div class="text source-text"><pre class="de1">constructed
constructed
constructed
constructed
constructed
constructed
arg.size() = 3
destructed
destructed
destructed
destructed
destructed
destructed</pre></div></div> 
</div>
<h3><span class="mw-headline" id=".E7.BC.BA.E9.99.B7.E6.8A.A5.E5.91.8A">缺陷报告</span></h3>
<p>下列更改行为的缺陷报告追溯地应用于以前出版的 C++ 标准。
</p>
<table class="dsctable" style="font-size:0.8em">
<tr>
<th> DR
</th>
<th> 应用于
</th>
<th> 出版时的行为
</th>
<th> 正确行为
</th></tr>
<tr>
<td> <a rel="nofollow" class="external text" href="https://wg21.cmeerw.net/cwg/issue2022">CWG 2022</a>
</td>
<td> C++14
</td>
<td> 常量表达式中复制消除曾为可选
</td>
<td> 强制复制消除
</td></tr>
<tr>
<td> <a rel="nofollow" class="external text" href="https://wg21.link/p1358r0#2278">CWG 2278</a>
</td>
<td> C++14
</td>
<td> 曾在常量表达式中强制 NRVO
</td>
<td> 在常量表达式中禁止 NRVO
</td></tr>
<tr>
<td> <a rel="nofollow" class="external text" href="https://wg21.link/p1968r0#2426">CWG 2426</a>
</td>
<td> C++17
</td>
<td> 返回纯右值时不要求析构函数
</td>
<td> 潜在调用析构函数
</td></tr></table>
<h3><span class="mw-headline" id=".E5.8F.82.E9.98.85">参阅</span></h3>
<ul><li> <a href="copy_initialization.html" title="cpp/language/copy initialization">复制初始化</a>
</li><li> <a href="copy_constructor.html" title="cpp/language/copy constructor">复制构造函数</a>
</li><li> <a href="move_constructor.html" title="cpp/language/move constructor">移动构造函数</a>
</li></ul>

<!-- 
NewPP limit report
Preprocessor visited node count: 2066/1000000
Preprocessor generated node count: 5914/1000000
Post‐expand include size: 45313/2097152 bytes
Template argument size: 15578/2097152 bytes
Highest expansion depth: 13/40
Expensive parser function count: 0/100
-->

<!-- Saved in parser cache with key mwiki1-mwiki_zh_:pcache:idhash:2696-0!*!0!!zh!*!zh!* and timestamp 20200310102652 -->
</div>                    <!-- /bodycontent -->
                                        <!-- printfooter -->
                    <div class="printfooter">
                    来自“<a href="https://zh.cppreference.com/mwiki/index.php?title=cpp/language/copy_elision&amp;oldid=65259">https://zh.cppreference.com/mwiki/index.php?title=cpp/language/copy_elision&amp;oldid=65259</a>”                    </div>
                    <!-- /printfooter -->
                                                            <!-- catlinks -->
                    <!-- /catlinks -->
                                                            <div class="visualClear"></div>
                    <!-- debughtml -->
                                        <!-- /debughtml -->
                </div>
                <!-- /bodyContent -->
            </div>
        </div>
        <!-- /content -->
        <!-- footer -->
        <div id="cpp-footer-base" class="noprint">
            <div id="footer">
                        <div id="cpp-navigation">
            <h5>导航</h5>
            <ul><li><a href="https://zh.cppreference.com/w/cpp/language/copy_elision">Online version</a></li><li>Offline version retrieved 2020-03-14 18:00.</li></ul></div>
                        <ul id="footer-info">
                                    <li id="footer-info-lastmod"> 本页面最后修改于2020年3月10日 (星期二) 03:26。</li>
                                    <li id="footer-info-viewcount">此页面已被浏览过11,302次。</li>
                            </ul>
                    </div>
        </div>
        <!-- /footer -->
        <script>if(window.mw){
mw.loader.state({"site":"loading","user":"missing","user.groups":"ready"});
}</script>
<script src="../../../common/skin_scripts.js"></script>
<script>if(window.mw){
mw.loader.load(["mediawiki.action.view.postEdit","mediawiki.user","mediawiki.page.ready","mediawiki.searchSuggest","mediawiki.hidpi","ext.gadget.MathJax","ext.gadget.ColiruCompiler"], null, true);
}</script>
<script src="../../../common/site_scripts.js"></script>
<script type="text/javascript">
var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-2828341-1']);
_gaq.push(['_setDomainName', 'cppreference.com']);
_gaq.push(['_trackPageview']);
</script><!-- Served in 0.081 secs. -->
	</body>
<!-- Cached 20200310134844 -->
</html>